package com.example.upload.tool;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 导出excel表格
 */
public class ExcelUtil {

    private static  final  String DEFAULT_NAME="导出数据";
    public static <T> void  doExport(HttpServletResponse response, String fileName, List<T> data, Class<T> type) throws IOException {
        response.setContentType("application/vnd.ms-excel");// 设置文本内省
        response.setCharacterEncoding("utf-8");// 设置字符编码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename="+encodedFileName+".xlsx"); // 设置响应头
        EasyExcel.write(response.getOutputStream(), type).sheet("1").doWrite(data); //用io流来写入数据
    }
    public static <T> void doExport(HttpServletResponse response, List<T> data, Class<T> type) throws IOException {
        doExport(response, DEFAULT_NAME, data, type);
    }

    public static <T> void  doDynamicExport(HttpServletResponse response, String fileName, List<T> data, List<List<String>> head) throws IOException {
        response.setContentType("application/vnd.ms-excel");// 设置文本内省
        response.setCharacterEncoding("utf-8");// 设置字符编码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename="+encodedFileName+".xlsx"); // 设置响应头
        EasyExcel.write(response.getOutputStream()).head(head).sheet("1").doWrite(data); //用io流来写入数据
    }
}
